package top.zerozoo.learn.grade.service.impl;

import top.zerozoo.learn.grade.dao.StudentBaseInfoDao;
import top.zerozoo.learn.grade.entity.StudentBaseInfo;
import top.zerozoo.learn.grade.factory.DaoFactory;
import top.zerozoo.learn.grade.service.StudentSimpleInfoService;
import top.zerozoo.learn.grade.vo.PageInfo;
import top.zerozoo.learn.grade.vo.StudentListCondition;
import top.zerozoo.learn.grade.vo.StudentSimpleInfo;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class StudentSimpleInfoServiceImpl implements StudentSimpleInfoService {
    private final StudentBaseInfoDao workerBaseInfoDao = DaoFactory.get(StudentBaseInfoDao.class);


    @Override
    public PageInfo<StudentSimpleInfo> find(int currentPage, int rows, StudentListCondition condition) {
        currentPage = Math.max(currentPage, 1);
        rows = Math.max(rows, 1);

        final PageInfo<StudentSimpleInfo> pageInfo = new PageInfo<>();

        final Map<String, String> conditionMap = condition.getConditionMap();

        final int start = (currentPage - 1) * rows;
        final List<StudentBaseInfo> studentBaseInfos = workerBaseInfoDao.find(start, rows, conditionMap);
        final List<StudentSimpleInfo> workerSimpleInfos = new LinkedList<>();
        for (StudentBaseInfo studentBaseInfo : studentBaseInfos) {
            workerSimpleInfos.add(StudentSimpleInfo.parse(studentBaseInfo));
        }

        final int totalCount = workerBaseInfoDao.count(conditionMap);
        final int totalPage = (totalCount % rows == 0) ? (totalCount / rows) : (totalCount / rows) + 1;

        pageInfo.setList(workerSimpleInfos);
        pageInfo.setCurrentPage(currentPage);
        pageInfo.setTotalCount(totalCount);
        pageInfo.setTotalPage(totalPage);

        return pageInfo;
    }
}
